package com.example.demo.handler;

import com.stanwind.wmqtt.WMHolder;
import com.stanwind.wmqtt.anno.TopicHandler;
import com.stanwind.wmqtt.handler.pool.MQTTMsg;
import com.stanwind.wmqtt.service.IMessageService;
import com.stanwind.wmqtt.utils.BaseTopicHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * DemoHandler
 *
 * @author : Stan
 * @version : 1.0
 * @date :  2021-02-03 3:24 PM
 **/
@Component
public class DemoHandler extends BaseTopicHandler {

    private static final Logger log = LoggerFactory.getLogger(DemoHandler.class);
    public static final String S_TOPIC_PUB = "IOT_SERVER";
    /* 上线消息 */
    public static final String S_TOPIC_STATUS_CONN = S_TOPIC_PUB + "/status/{deviceId}/connected";
    /* 下线消息 */
    public static final String S_TOPIC_STATUS_DISCONN = S_TOPIC_PUB + "/status/{deviceId}/disconnected";

    @Autowired
    private IMessageService messageService;

    @Autowired
    private WMHolder wmHolder;

    /**
     * 协议设定
     *
     * @param msg
     */
    @TopicHandler(topic = S_TOPIC_STATUS_CONN)
    public void online(MQTTMsg msg) throws InterruptedException {
        log.info("device {} online -> [{}]", getSn(), msg);

        Thread.sleep(2000);
//        producerHolder.addTopic("");
        messageService.notifyToTopic("IOT_CLIENT/abcd", "hello world");
    }

    /**
     * 协议设定
     *
     * @param msg
     */
    @TopicHandler(topic = S_TOPIC_STATUS_DISCONN)
    public void offline(MQTTMsg msg) {
        log.info("device {} offline -> {}", getSn(), msg);
    }

    /**
     * 需要EMQTT支持
     *
     * @param msg
     */
    @TopicHandler(topic = "$SYS/brokers/{node}/clients/{deviceId}/connected")
    public void connected(MQTTMsg msg) {
        log.info("device {} connected to {} -> {}", getParam("deviceId"), getParam("node"), msg);
    }

    /**
     * 需要EMQTT支持
     *
     * @param msg
     */
    @TopicHandler(topic = "$SYS/brokers/{node}/clients/{deviceId}/disconnected")
    public void disconnected(MQTTMsg msg) {
        log.info("device disconnected -> {}", msg);
    }

    @TopicHandler(topic = "$SYS/brokers/{node}/datetime")
    public void time(MQTTMsg msg) {
        log.debug("node [{}] time [{}]", getParam("node"), msg.getPayload());
    }

    @TopicHandler(topic = "$SYS/brokers/{node}/uptime")
    public void uptime(MQTTMsg msg) {
        log.debug("node [{}] uptime [{}]", getParam("node"), msg.getPayload());
    }
}
